package com.ruijie.acl.web.validator;

import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang.StringUtils;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Validator;

import com.ruijie.acl.service.AccessGroupService;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.foundation.international.MessageSupport;

/**
 * <p>
 * Title: ACL组名称验证
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * ACL组名称合法性验证
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-07-14
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */
@Name("groupNameValueValidator")
@Validator
public class GroupNameValidator extends MessageSupport implements
		javax.faces.validator.Validator {

	@In private Map<String, String> messages;
	@In("#{accessGroupService}")
	private AccessGroupService accessGroupService;

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String text = value.toString().trim();
		
		// 组名合法性验证：只能是英文(可含_)或数值
		// 标准IP访问列表，编号为1 - 99，1300 - 1999
		// 扩展IP访问列表，编号为100-199，2000 - 2699
		// MAC 扩展访问列表，编号为700-799 
		// Expert 扩展访问列表，编号为2700-2899

		if(component.getAttributes().get("required").toString().equals("true")){
			if(!StringUtils.isNotEmpty(text.replaceAll("　",   " ").trim())){
				throw new ValidatorException(new FacesMessage(messages.get("javax.faces.component.UIInput.REQUIRED")));
			}
		}
		if(text.indexOf(" ")>=0){
			//不能含有空格
			throw new ValidatorException(new FacesMessage(
					getI18NMessage("acl_validator_group_name_no_blank")));
		}
		if (AclUtil.isNotCNAndFullChar(text)) {
			String validateResult = AclUtil.validateGroupName(text, component.getAttributes().get("groupType").toString());
			if(validateResult.length()>0){
				throw new ValidatorException(
						new FacesMessage(
								getI18NMessage(validateResult)));
			}
		}else{
			throw new ValidatorException(new FacesMessage(
					getI18NMessage("acl_validator_group_name_en_num")));
		}

		Long groupId = (Long) component.getAttributes().get("groupId");
		if (accessGroupService.isExistGroupName(text, groupId)) {
			throw new ValidatorException(new FacesMessage(
					getI18NMessage("acl_validator_group_name")));
		}
	}
}
